import 'dart:io';
import 'dart:developer' as developer;

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:xindong/common/xindong_sezhi.dart';
import 'package:xindong/common/xindong_all.dart';
import 'package:xindong/widgets/xindong_loading.dart';

// 全局Key
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

// 全局上下文
BuildContext currentContext() {
  if (navigatorKey.currentState?.overlay?.context != null) {
    return navigatorKey.currentState!.overlay!.context;
  }
  return navigatorKey.currentContext!;
}

void mDebugPrint(var text) {
  if (!kReleaseMode) {
    if (Platform.isAndroid) {
      developer.log(text);
    } else {
      debugPrint("$text", wrapWidth: 200);
    }
  }
}

void mCatchPrint(var e) {
  if (!kReleaseMode) {
    if (Platform.isAndroid) {
      developer.log("异常$e");
    } else {
      print(e);
    }
  }
}

void showToast(String? message, {int milliseconds = 2000}) {
  if (message == null || message.isEmpty || XinDongAll.instance.smartDialogInitialized == false) {
    return;
  }
  try {
    SmartDialog.showToast(
      message,
      alignment: Alignment.center,
      displayType: SmartToastType.last, // 连续调用toast，后一条toast会顶掉前一条toast
      displayTime: Duration(milliseconds: milliseconds),
      builder: (BuildContext context) {
        return Container(
          padding: const EdgeInsets.all(10),
          margin: const EdgeInsets.only(left: 16, right: 16),
          decoration: BoxDecoration(
            color: DZColors.maskColor,
            borderRadius: BorderRadius.circular(10),
          ),
          child: Text(
            message,
            textAlign: TextAlign.center,
            style: const TextStyle(fontSize: 15, color: Colors.white, height: 1.2),
          ),
        );
      },
    );
  } catch (error) {
    mDebugPrint(error);
  }
}

void showLoading({Color? maskColor, bool showLoading = true}) {
  SmartDialog.showLoading(
    backDismiss: false,
    clickMaskDismiss: false,
    useAnimation: true,
    maskColor: maskColor,
    builder: (BuildContext context) {
      // 添加长按隐藏
      return GestureDetector(
        onLongPress: () => hideLoading(),
        behavior: HitTestBehavior.opaque,
        child: showLoading ?const XinDongLoadingCenter() : const SizedBox(),
      );
    },
  );
}

void hideLoading() {
  SmartDialog.dismiss(status: SmartStatus.loading);
}
